package com.fire.control.system.support.util;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.fire.control.system.entity.File;

/**
 * 
 * @ClassName:  FileUtil
 * @Description:  文件处理工具类
 * @author:  xiechengguang
 * @date:  2017年5月23日 下午3:36:08
 *
 */
public class FileUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);
	
	public static List<File> uploadFile(MultipartHttpServletRequest request){
		List<File> files = new ArrayList<File>(); 
		MultiValueMap<String, MultipartFile> map = request.getMultiFileMap();
		for (String key : map.keySet()) {
			List<MultipartFile> list = map.get(key);
			if(list != null && list.isEmpty() == false) {
	            for (MultipartFile multifile : list) { 
	            	File file = uploadFile(multifile);
	            	files.add(file);
	            }
	        }
		}
		return files;
	}
	
	/*public List<AppFileVo> uploadFile(MultipartHttpServletRequest request) {
		List<AppFileVo> fileVos = new ArrayList<AppFileVo>(); 
		MultiValueMap<String, MultipartFile> map = request.getMultiFileMap();
		for (String key : map.keySet()) {
			List<MultipartFile> list = map.get(key);
			if(list != null && list.isEmpty() == false) {
	            for (MultipartFile mFile : list) { 
	            	String originalFileName= mFile.getOriginalFilename();//获取文件名称[含后缀名]
	            	if(originalFileName != null) {
	            		String suffixName = originalFileName.substring(originalFileName.lastIndexOf(".")+1); //后缀名
	            		if(!("jpg".equals(suffixName) || "JPG".equals(suffixName) || "jpeg".equals(suffixName) || "JPEG".equals(suffixName) || 
	            		   "png".equals(suffixName) || "PNG".equals(suffixName) || "gif".equals(suffixName) || "GIF".equals(suffixName))) {
	                		continue;
	                	}
	            		File file = uploadFile(mFile);
	            		File savedFile = fileRepository.save(file); // 保存文件到数据库
	            		
	            		if(savedFile != null) {
	            			AppFileVo vo = new AppFileVo();
	                		vo.setId(savedFile.getId());
	                		vo.setUrl(savedFile.getAccessAddress()); //最终应该是getAccessAddress()
	                		fileVos.add(vo);
	            		}
	            	}
	            }
	        }
			
		}
        
	}*/
	
	public static File uploadFile(MultipartFile multifile) {
		
		File file = new File();
		String year = DateTimeFormatter.ofPattern("yyyy").format(LocalDate.now());
        String monthDay = DateTimeFormatter.ofPattern("MM-dd").format(LocalDate.now());
        String staticPath = year+"/"+monthDay+"/";
        String path = StaticValue.file_upload_path+staticPath;
        CCRDFile.createDir(path);
		
        if (!multifile.isEmpty()) {
        	Long size = multifile.getSize(); //文件大小
        	String originalFileName = multifile.getOriginalFilename();//获取文件名称(含后缀名)
        	String suffixName = originalFileName.substring(originalFileName.lastIndexOf(".")+1); //后缀名
    		String realName = originalFileName.substring(0, originalFileName.lastIndexOf("."));  //文件名
    		String newFileName = realName+"_"+UUID.randomUUID().toString().replace("-", "")+"."+suffixName;//新文件名称(含后缀)
        	
    		file.setSize(size);
    		file.setSuffix(suffixName);
    		file.setName(realName);
    		file.setPhysicalAddress((path+newFileName).replace("\\", "/"));
    		file.setAccessAddress(("/"+staticPath+newFileName).replace("\\", "/"));
    		
            try {
                byte[] bytes = multifile.getBytes();
                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new java.io.File(file.getPhysicalAddress())));
                stream.write(bytes);
                stream.close();
            } catch (Exception e) {
            	logger.info("保存文件失败");
            }
        }
        return file;
		 
	}
	
	/**
	 * @Title: saveFile   
	 * @Description: 保存文件  
	 * @param:       
	 * @return: String       
	 * @throws
	 */
	/*public static String saveFile(MultipartFile multifile, String path) {
		try {
			// 创建目录  
			CCRDFile.createDir(path);
	        // 读取文件流并保持在指定路径  
	        InputStream inputStream = multifile.getInputStream();  
	        OutputStream outputStream = new FileOutputStream(path + multifile.getOriginalFilename());  
	        byte[] buffer = multifile.getBytes();  
	        int bytesum = 0;  
	        int byteread = 0;  
	        while ((byteread = inputStream.read(buffer)) != -1) {  
	            bytesum += byteread;  
	            outputStream.write(buffer, 0, byteread);  
	            outputStream.flush();  
	        }  
	        outputStream.close();  
	        inputStream.close();  
	  
	        return path + multifile.getOriginalFilename(); 
		} catch(Exception e) {
			System.out.println("保存文件失败");
			return null;
		}
		 
	}*/
	
	/**
	 * @Title: deleteFile   
	 * @Description: 删除文件  
	 * @param:        
	 * @return: boolean      
	 * @throws
	 */
	public static boolean deleteFile(String file, String path) {
		try {
			boolean success = Boolean.FALSE;  
	        java.io.File f = new java.io.File(path+file);  
	        if (f.exists()) {  
	           f.delete();  
	           success = Boolean.TRUE;  
	        }  
	        return success;  
		} catch(Exception e) {
			logger.info("删除文件失败");
			return false;
		}
		
	}
}
